#include <QtGui>
#include <QStandardItemModel>

#include "testMainWindow.h"

#include "records.h"
#include "stream.h"
#include "stdfFile.h"

#include <iostream>
#include <sstream>

#include <boost/progress.hpp>

using namespace stdf;

TestMainWindow::TestMainWindow()
{
     init();
     setCurrentFile("");
}

TestMainWindow::TestMainWindow(const QString &fileName)
{
    init();
    loadFile(fileName);
}

void TestMainWindow::closeEvent(QCloseEvent *event) {
}

 void TestMainWindow::newFile()
{
    TestMainWindow *other = new TestMainWindow;
    other->move(x() + 40, y() + 40);
    other->show();
}

void TestMainWindow::open()
{
    QString fileName = QFileDialog::getOpenFileName(this);
    if (!fileName.isEmpty()) {
        TestMainWindow *existing = findMainWindow(fileName);
        if (existing) {
            existing->show();
            existing->raise();
            existing->activateWindow();
            return;
        }

         if (isUntitled && textEdit->document()->isEmpty()
                 && !isWindowModified()) {
             loadFile(fileName);
         } else {
             TestMainWindow *other = new TestMainWindow(fileName);
             if (other->isUntitled) {
                 delete other;
                 return;
             }
             other->move(x() + 40, y() + 40);
             other->show();
         }
     }
 }

 bool TestMainWindow::save()
 {
     if (isUntitled) {
         return saveAs();
     } else {
         return saveFile(curFile);
     }
 }

 bool TestMainWindow::saveAs()
 {
     QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),
                                                     curFile);
     if (fileName.isEmpty())
         return false;

     return saveFile(fileName);
 }

void TestMainWindow::about()
{
   QMessageBox::about(this, tr("About TestStdfFile"),
             tr("The <b>TestStdfFile</b> example demonstrates how to write single "
                "document interface applications using Qt."));
}


void TestMainWindow::documentWasModified()
 {
     setWindowModified(true);
 }

 void TestMainWindow::init()
 {
     setAttribute(Qt::WA_DeleteOnClose);

     isUntitled = true;

     tabWidget = new QTabWidget;
     textEdit = new QTextEdit;
     tableView = new QTableView;
     tableView->setModel(&model);

     tabWidget->addTab( textEdit, "Records");
     tabWidget->addTab( tableView, "Table");

     setCentralWidget(tabWidget);

     createActions();
     createMenus();
     createToolBars();
     createStatusBar();

     readSettings();

     connect(textEdit->document(), SIGNAL(contentsChanged()),
             this, SLOT(documentWasModified()));

     setUnifiedTitleAndToolBarOnMac(true);
 }

void TestMainWindow::createActions()
 {
     newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
     newAct->setShortcuts(QKeySequence::New);
     newAct->setStatusTip(tr("Create a new file"));
     connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));

     openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
     openAct->setShortcuts(QKeySequence::Open);
     openAct->setStatusTip(tr("Open an existing file"));
     connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

     saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
     saveAct->setShortcuts(QKeySequence::Save);
     saveAct->setStatusTip(tr("Save the document to disk"));
     connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));

     saveAsAct = new QAction(tr("Save &As..."), this);
     saveAsAct->setShortcuts(QKeySequence::SaveAs);
     saveAsAct->setStatusTip(tr("Save the document under a new name"));
     connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));

     closeAct = new QAction(tr("&Close"), this);
     closeAct->setShortcut(tr("Ctrl+W"));
     closeAct->setStatusTip(tr("Close this window"));
     connect(closeAct, SIGNAL(triggered()), this, SLOT(close()));

     exitAct = new QAction(tr("E&xit"), this);
     exitAct->setShortcut(tr("Ctrl+Q"));
     exitAct->setStatusTip(tr("Exit the application"));
     connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));

     aboutAct = new QAction(tr("&About"), this);
     aboutAct->setStatusTip(tr("Show the application's About box"));
     connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

     aboutQtAct = new QAction(tr("About &Qt"), this);
     aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
     connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

 }

void TestMainWindow::createMenus()
 {
     fileMenu = menuBar()->addMenu(tr("&File"));
     fileMenu->addAction(newAct);
     fileMenu->addAction(openAct);
     fileMenu->addAction(saveAct);
     fileMenu->addAction(saveAsAct);
     fileMenu->addSeparator();
     fileMenu->addAction(closeAct);
     fileMenu->addAction(exitAct);

     menuBar()->addSeparator();

     helpMenu = menuBar()->addMenu(tr("&Help"));
     helpMenu->addAction(aboutAct);
     helpMenu->addAction(aboutQtAct);
 }

 void TestMainWindow::createToolBars()
 {
     fileToolBar = addToolBar(tr("File"));
     fileToolBar->addAction(newAct);
     fileToolBar->addAction(openAct);
     fileToolBar->addAction(saveAct);

 }

 void TestMainWindow::createStatusBar()
 {
     statusBar()->showMessage(tr("Ready"));
 }


void TestMainWindow::readSettings()
 {
     QSettings settings("Trolltech", "SDI Example");
     QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
     QSize size = settings.value("size", QSize(400, 400)).toSize();
     move(pos);
     resize(size);
 }

 void TestMainWindow::writeSettings()
 {
     QSettings settings("Trolltech", "SDI Example");
     settings.setValue("pos", pos());
     settings.setValue("size", size());
 }



 bool TestMainWindow::maybeSave()
 {
     if (textEdit->document()->isModified()) {
         QMessageBox::StandardButton ret;
         ret = QMessageBox::warning(this, tr("SDI"),
                      tr("The document has been modified.\n"
                         "Do you want to save your changes?"),
                      QMessageBox::Save | QMessageBox::Discard
                      | QMessageBox::Cancel);
         if (ret == QMessageBox::Save)
             return save();
         else if (ret == QMessageBox::Cancel)
             return false;
     }
     return true;
 }


 void TestMainWindow::loadFile(const QString &fileName)
 {

    StdfFile stdfFile( fileName.toStdString(), ReadOnly);
    stdfFile.open(fileName.toStdString(), ReadOnly);
    std::vector< std::vector<std::string> > data, headerData;
    stringstream ss;
    streambuf* stream_buffer = cout.rdbuf();
    //cout.rdbuf(ss.rdbuf());
    {
        boost::progress_timer t;
        stdfFile.read(data, headerData);
    }
    {
        unsigned int nRows=data.size();
        unsigned int nCols=0;
        if(nRows > 0)
            unsigned int nCols = data[0].size();
        model.clear();

        for(unsigned int col=0; col < nCols; col++)
            model.insertColumn(col);

        for(unsigned int i = 0; i < nRows; i++) {
            QList<QStandardItem *> rowItems;
            for(unsigned int j=0; j < data[i].size(); j++) {
                //cout << data[i][j] << "\t";
                QStandardItem *item = new QStandardItem(QString(data[i][j].c_str()));
                rowItems.append(item);
            }
            model.appendRow(rowItems);
            //cout << endl;
        }
            if(headerData.size() > 0) {
                QStringList labels;
                for(unsigned int i=0; i < headerData[0].size(); i++)
                    labels.append(QString(headerData[0][i].c_str()));
                model.setHorizontalHeaderLabels(labels);
            }
    }
    //cout.rdbuf(stream_buffer);
    stdfFile.close();

    string tempStr = ss.str();

    QApplication::setOverrideCursor(Qt::WaitCursor);
    textEdit->setPlainText(QString::fromStdString(tempStr));
    QApplication::restoreOverrideCursor();
#if 0
     if (!file.open(QFile::ReadOnly | QFile::Text)) {
         QMessageBox::warning(this, tr("SDI"),
                              tr("Cannot read file %1:\n%2.")
                              .arg(fileName)
                              .arg(file.errorString()));
         return;
     }

     QTextStream in(&file);
     QApplication::setOverrideCursor(Qt::WaitCursor);
     textEdit->setPlainText(in.readAll());
     QApplication::restoreOverrideCursor();

#endif
     setCurrentFile(fileName);
     statusBar()->showMessage(tr("File loaded"), 2000);
 }

 bool TestMainWindow::saveFile(const QString &fileName)
 {
     QFile file(fileName);
     if (!file.open(QFile::WriteOnly | QFile::Text)) {
         QMessageBox::warning(this, tr("SDI"),
                              tr("Cannot write file %1:\n%2.")
                              .arg(fileName)
                              .arg(file.errorString()));
         return false;
     }

     QTextStream out(&file);
     QApplication::setOverrideCursor(Qt::WaitCursor);
     out << textEdit->toPlainText();
     QApplication::restoreOverrideCursor();

     setCurrentFile(fileName);
     statusBar()->showMessage(tr("File saved"), 2000);
     return true;
 }

 void TestMainWindow::setCurrentFile(const QString &fileName)
 {
     static int sequenceNumber = 1;

     isUntitled = fileName.isEmpty();
     if (isUntitled) {
         curFile = tr("document%1.stdf").arg(sequenceNumber++);
     } else {
         curFile = QFileInfo(fileName).canonicalFilePath();
     }

     textEdit->document()->setModified(false);
     setWindowModified(false);

     setWindowTitle(tr("%1[*] - %2").arg(strippedName(curFile))
                                        .arg(tr("SDI")));
 }



 QString TestMainWindow::strippedName(const QString &fullFileName)
 {
     return QFileInfo(fullFileName).fileName();
 }

 TestMainWindow *TestMainWindow::findMainWindow(const QString &fileName)
 {
     QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();

     foreach (QWidget *widget, qApp->topLevelWidgets()) {
         TestMainWindow *mainWin = qobject_cast<TestMainWindow *>(widget);
         if (mainWin && mainWin->curFile == canonicalFilePath)
             return mainWin;
     }
     return 0;
 }
